package ccnt.pvc.scudwaremobile.activity;

import java.util.ArrayList;
import java.util.Map;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import ccnt.pvc.scudwaremobile.R;
import ccnt.pvc.scudwaremobile.coop.ScudwareUPnPService;
import ccnt.pvc.scudwaremobile.coop.ScudwareUPnPServiceImpl;

public class CoopActivity extends Activity {

	private ScudwareUPnPService upnpService;

	Button btnRefresh;
	ListView listDevices;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_coop);

		initView();
		initService();
	}
	
	private void initService() {
		bindService(new Intent(CoopActivity.this, ScudwareUPnPServiceImpl.class),
				serviceConnection, BIND_AUTO_CREATE);
	}
	
	private void initView() {
		btnRefresh = (Button)findViewById(R.id.btnRefresh);
		btnRefresh.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final Map<String, String> devices = upnpService.getScudwares();
				final ArrayList<String> list = new ArrayList<String>();
				for(String account : devices.keySet()) {
					list.add(account + " : " + devices.get(account));
				}
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(
						getApplicationContext(),
						android.R.layout.simple_list_item_1, list);
				listDevices.setAdapter(adapter);
				
				listDevices.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						String accout = list.get(arg2).split(" : ")[0];
						String ip = devices.get(accout);
						Intent intent = new Intent(CoopActivity.this, CoopServiceListActivity.class);
						intent.putExtra("account", accout);
						intent.putExtra("ip", ip);
						startActivity(intent);
					}
					
				});
			}
			
		});
		
		listDevices = (ListView)findViewById(R.id.listDevices);
	}

	@Override
	protected void onDestroy() {
		upnpService.disableFound();
		unbindService(serviceConnection);
		super.onDestroy();
	}
	
	private ServiceConnection serviceConnection = new ServiceConnection() {

	    public void onServiceConnected(ComponentName className, IBinder service) {
	        upnpService = (ScudwareUPnPService) service;
	        upnpService.enableFound();
	        
	        // Search asynchronously for all devices
	        upnpService.getControlPoint().search();
	    }

	    public void onServiceDisconnected(ComponentName className) {
	        upnpService = null;
	    }
	};
}
